package com.thomas.uphtm;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.thomas.tool.ImageUtil;

/**
 * 从 http://www.uphtm.com/ 下载图片
 * @author thomas
 *
 */
public class DownloadImagesFromUpHtm {
	
	/**
	 * 根据类别保存图片
	 * @param id
	 * @return
	 */
	public static boolean saveImageByCategoryId(String id, String subId) {

		// http://www.uphtm.com/beauty-leg-486.html
		// http://www.uphtm.com/beauty-leg-486.html/8
		// http://www.uphtm.com/beauty-leg-300.html
		// http://www.uphtm.com/beauty-leg-300.html/2

		String siteBaseUrl  = "http://www.uphtm.com";
		String pageUrl = siteBaseUrl + "beauty-leg-" + id + ".html";
		if (subId != null && subId.equals("") != true) {
			pageUrl += subId; 
		}
		System.out.println(pageUrl);
		
		
		try {
			String userAgent = "Chrome/45.0.2454.81 Safari/537.36";
			Document doc = Jsoup.connect(pageUrl).timeout(36000).userAgent(userAgent).get();
			String title = doc.title().split("_")[0];
			String saveName = id + "_" + title + ".jpg";
			String imageUrl = siteBaseUrl + doc.select(".viewpic>img").attr("src");
			return ImageUtil.saveImageByUrl(imageUrl, saveName);
		} catch (Exception e) {
			System.out.println(id + " time out!");
			return false;
		}

	}
	
	/**
	 * 保存图片线程
	 * @param i 类别ID
	 */
	public static void save(String i) {
		
		boolean isSuccess = DownloadImagesFromUpHtm.saveImageByCategoryId(i+"", "");
		
		if (isSuccess != true) {
			System.out.println("skip "+i+" ...");
			return;
		}
		
		for (int k=2; k<20; k++) {
			new SaveImageThreadTool(i, k+"").start();
		}
	}
	
	/**
	 * 执行的主函数
	 * @param args
	 */
	public static void main(String[] args) {
		
		// min = 1
		// cur = 1
		// max = 9999
		for (int i=1170; i<9999; i++) {
			//DownloadImagesFromUpHtm.save(i+"");
		}
		DownloadImagesFromUpHtm.save(200+"");
	}
}


//保存图片线程
class SaveImageThreadTool extends Thread {
	
	private String saveCateId = "";
	private String subCateId  = "";

	public SaveImageThreadTool(String saveCateId, String subCateId) {
		super();
		this.saveCateId = saveCateId;
		this.subCateId  = subCateId;
	}

	public void run() {
		DownloadImagesFromUpHtm.saveImageByCategoryId(this.saveCateId, this.subCateId);
	}
	
}
